<template>
    <section class="communityCloud">
       
            <img src="@/assets/img/console/instance-nodata.png" alt="">
        
        <!-- <a-spin :spinning="loading">
            <div class="page-header">
                <a-space>
                    <a-select ref="select" :bordered="false" v-model:value="form.regionId" placeholder="区域" allowClear
                        style="width: 180px" class="icon-select region">
                        <a-select-option v-for="item in regions" :value="item.regionId">{{ item.regionName
                        }}</a-select-option>
                    </a-select>

                    <a-select ref="select" :bordered="false" v-model:value="form.netSpeed" placeholder="网络" allowClear
                        style="width: 180px" class="icon-select netSpeed">
                        <a-select-option value="0">低-任意</a-select-option>
                        <a-select-option value="40">中-40Mb/s以上</a-select-option>
                        <a-select-option value="100">高-100Mb/s以上</a-select-option>
                    </a-select>
                </a-space>
            </div>

            <div class="page-key-search">
                <a-row :gutter="24">
                    <a-col :span="6">
                        <a-form-item>
                            <div style="display: flex;max-width: 100%;">
                                <label style="display: flex;align-items: center;" class="item-label">
                                    <span>vCPUs</span>
                                    <a-tooltip placement="top" title="每个GPU的最小CPU数量">
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-input v-model="form.cpuNum"></a-input>
                            </div>
                        </a-form-item>
                    </a-col>

                    <a-col :span="6">
                        <a-form-item>
                            <div style="display: flex;">
                                <label style="display: flex;align-items: center;" class="item-label">
                                    <div style="width: 30px;">内存</div>
                                    <a-tooltip placement="top" title="每个GPU分配到的内存">
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-select ref="select" v-model:value="form.memory" allowClear>
                                    <a-select-option value="8">8</a-select-option>
                                    <a-select-option value="16">16</a-select-option>
                                    <a-select-option value="24">24</a-select-option>
                                    <a-select-option value="48">48</a-select-option>
                                    <a-select-option value="80">80</a-select-option>
                                    <a-select-option value="100">100</a-select-option>
                                </a-select>
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item>
                            <div class="flex">
                                <label style="display: flex;align-items: center;" class="item-label">
                                    <div class="mr-8">硬盘类型</div>
                                </label>
                                <a-radio-group v-model:value="form.diskType" name="radioGroup">
                                    <a-radio value="SSD">SSD</a-radio>
                                    <a-radio value="NVME">NVME</a-radio>
                                </a-radio-group>
                            </div>

                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item>
                            <div class="flex">
                                <label style="display: flex;align-items: center;" class="item-label">
                                    <div style="width:80px;" class="mr-8">CUDA版本</div>
                                </label>
                                <a-select ref="select" v-model:value="form.toolVersion" allowClear>
                                    <a-select-option v-for="item in cuda" :value="item">{{ item }}</a-select-option>
                                </a-select>
                            </div>

                        </a-form-item>
                    </a-col>
                </a-row>
            </div>

            <div class="page-content">
                <div class="page-global-header">
                    <div class="page-global-title">基础配置</div>
                </div>

                <a-form-item label="">
                    <div style="display: flex;max-width: 100%;">
                        <label style="display: flex;width: 140px;" class="item-label">
                            <span>计费模式</span>
                            <QuestionCircleOutlined style="margin:4px 8px 0 4px;color: #D7D9DD;"
                                @click="openBillTypeDocs" />
                        </label>

                        <div class="billing-modes">
                            <div class="billing-mode-card" :class="{ 'active-mode-card': currentSkuName == '0' }"
                                @click="changeSkuName(0, 'payg')">
                                <div class="card-img">
                                    <img src="@/assets/img/console/icon_to_number.png" alt="">
                                </div>
                                <div class="card-info">
                                    <div>按量计费</div>
                                    <p>适用需求量有大幅波动的业务</p>
                                </div>
                            </div>

                            <div class="billing-mode-card" :class="{ 'active-mode-card': currentSkuName == '1' }"
                                @click="changeSkuName(1, 'bidding')">
                                <div class="card-img">
                                    <img src="@/assets/img/console/icon_competitive_price.png" alt="">
                                </div>
                                <div class="card-info">
                                    <div>竞价实例</div>
                                    <p>更节约成本，但实例有<span style="color:#FF3838;">被自动释放的风险</span></p>
                                </div>
                            </div>

                            <div class="billing-mode-card" :class="{ 'active-mode-card': currentSkuName == '2' }"
                                @click="changeSkuName(2, 'daily')">
                                <div class="card-img">
                                    <img src="@/assets/img/console/icon_daily.png" alt="">
                                </div>
                                <div class="card-info">
                                    <div>包天</div>
                                    <p>适合需求量稳定，需求量为天的业务</p>
                                </div>
                            </div>

                            <div class="billing-mode-card" :class="{ 'active-mode-card': currentSkuName == '3' }"
                                @click="changeSkuName(3, 'weekly')">
                                <div class="card-img">
                                    <img src="@/assets/img/console/icon_weekly.png" alt="">
                                </div>
                                <div class="card-info">
                                    <div>包周</div>
                                    <p>适合需求量稳定，需求量为周的业务</p>
                                </div>
                            </div>

                            <div class="billing-mode-card" :class="{ 'active-mode-card': currentSkuName == '4' }"
                                @click="changeSkuName(4, 'monthly')">
                                <div class="card-img">
                                    <img src="@/assets/img/console/icon_m_sub.png" alt="">
                                </div>
                                <div class="card-info">
                                    <div>包月</div>
                                    <p>适合需求量稳定，需求量为月的业务</p>
                                </div>
                            </div>

                        </div>
                    </div>
                </a-form-item>

                <a-form-item label="活动标签" :colon="false">
                    <a-space>
                        <a-checkbox-group v-model:value="form.activeTag" style="width: 100%">
                            <a-checkbox v-for="item in activeTags" :value="item.id">{{ item.name }}</a-checkbox>
                        </a-checkbox-group>
                        <RedoOutlined :style="{ color: '#07F' }" @click="form.activeTag = []" />
                    </a-space>
                </a-form-item>

                <a-form-item label="机器特性" :colon="false">
                    <a-space>
                        <a-checkbox-group v-model:value="form.tags" style="width: 100%">
                            <a-checkbox v-for="item in tags" :value="item.id">{{ item.name }}</a-checkbox>
                        </a-checkbox-group>
                        <RedoOutlined :style="{ color: '#07F' }" @click="form.tags = []" />
                    </a-space>
                </a-form-item>

                <a-form-item label="显卡类型" :colon="false">
                    <a-form-item>
                        <div class="gpu-types">
                            <div class="gpu-type-card" v-for="(item, index) in gpuInfos"
                                :class="{ 'active-gpu-card': currentGpUName == index, 'disabled-gpu-card': item.gpuNum == 0 || !item.gpuNum }"
                                @click="item.gpuNum && chooseGpu(index, item.name)">
                                <div class="title">{{ item.name }}</div>
                                <p>{{ item.vram }}GB VRAM</p>
                                <div class="sale-tag" v-if="item.tagName">{{ item.tagName }}</div>
                            </div>
                        </div>
                    </a-form-item>

                    <a-form-item>
                        <div class="ram flex">
                            <div class="mr-8">数据盘：50GB</div>
                            <a-checkbox v-model:checked="isExpansion">需要扩容</a-checkbox>
                        </div>
                    </a-form-item>

                    <a-form-item label="" v-if="isExpansion">
                        <div class="expansion">
                            <a-space>
                                <span>最大可扩容至</span>
                                <a-input-number style="width:180px;" v-model:value="costForm.DataDisk" :placeholder="`可变更范围为50~${maxDataDisk}`" :min="50" :max="maxDataDisk" />
                                <span>GB</span>
                            </a-space>

                            <div class="instance-tips" style="margin-left: 24px;">
                                <InfoCircleFilled class="mr-8" />付费数据盘开机时将按 每小时<span class="fee-style">¥{{
                                    accountInfo?.runningInstanceStoragePrice }}</span>/GB进行计费，关机时 将按每小时<span
                                    class="fee-style">¥{{
                                        accountInfo?.stopInstanceStoragePrice }}</span>进行计费。
                            </div>
                        </div>
                    </a-form-item>

                    <a-form-item>
                        <div class="ram flex">
                            <div class="mr-8">系统盘：30GB</div>
                        </div>
                    </a-form-item>

                </a-form-item>

                <a-form-item label="GPU数量" :colon="false">
                    <a-row :gutter="24">
                        <a-col :span="8" class="gpuNum">
                            <div class="tooltip">{{ form.gpuNum }}</div>
                            <a-slider v-model:value="form.gpuNum" :marks="marks" :min="1" :max="10"
                                :tooltip-visible="false"></a-slider>
                        </a-col>
                    </a-row>
                </a-form-item>

                <a-form-item>
                    <a-table :dataSource="dataSource" :columns="columns" :pagination="false" bordered
                        :locale="{ emptyText: '暂无可用机器，可联系客服上架' }">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.key === 'gpuNum'">
                                <div>{{ record.gpuNum - record.gpuUsedNum }} </div>
                            </template>
                            <template v-if="column.key === 'netUploadSpeed'">
                                <div>U: {{ unitGBS(record.netUploadSpeed) }} </div>
                                <div> D: {{ unitGBS(record.netDownloadSpeed) }}</div>
                            </template>
                            <template v-if="column.key === 'memorySize'">
                                <div>{{ printSize(record.memorySize) }} </div>
                            </template>
                            <template v-if="column.key === 'price'">
                                <div> ￥{{ record.price }} ({{ (10 * (record.discount) == 0 || 10 * (record.discount) == 10)
                                    ? '-' : 10 * (record.discount)
                                }})折</div>
                            </template>
                            <template v-if="column.key === 'payByVoucher'">
                                <div>{{ record.payByVoucher == 1 ? '是' : '否' }} </div>
                            </template>
                        </template>
                    </a-table>
                </a-form-item>

                <a-form-item label="">
                    <a-form-item>
                        <div style="display: flex;max-width: 100%;">
                            <label style="display: flex;width: 140px;" class="item-label">
                                <span>实例镜像</span>
                                <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" @click="openImageDocs" />
                            </label>
                            <a-radio-group v-model:value="imageType" @change="changeImageType">
                                <a-radio :value="1">官方镜像</a-radio>
                                <a-radio :value="2">我的镜像</a-radio>
                            </a-radio-group>
                        </div>
                    </a-form-item>

                    <a-form-item v-if="imageType == 1">
                        <a-row :gutter="24" style="margin-left:130px;">
                            <a-col :span="8">
                                <a-cascader v-model:value="costForm.image" :options="financialImageList"
                                    @change="selectImageId" placeholder="请选择框架名称/框架版本/Cuda版本/Python版本" />
                            </a-col>
                        </a-row>
                    </a-form-item>

                    <a-form-item v-if="imageType == 2">
                        <a-row :gutter="24" style="margin-left:130px;">
                            <a-col :span="8">
                                <a-select ref="select" v-model:value="costForm.imageId" allowClear>
                                    <a-select-option v-for="item in personalImageList" :value="item.imageId">{{
                                        item.imageName
                                    }}</a-select-option>
                                </a-select>
                            </a-col>
                        </a-row>
                    </a-form-item>
                </a-form-item>

                <div class="page-global-header">
                    <div class="page-global-title">高级配置</div>
                    <a style="font-size: 14px;color: #999;" @click="expand = !expand">
                        <template v-if="expand">
                            <UpOutlined />
                        </template>
                        <template v-else>
                            <DownOutlined />
                        </template>
                    </a>
                </div>

                <div v-if="expand">
                    <a-col :span="10">
                        <a-form-item>
                            <div style="display: flex;max-width: 100%;">
                                <label style="display: flex;width: 180px;" class="item-label">
                                    <span>环境变量</span>
                                    <a-tooltip placement="top"
                                        title="添加在实例内可使用的环境变量，可以指定多个，多个环境变量分号分隔，每个环境变量使用 KEY=value 的形式定义">
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-input v-model:value="costForm.advancedConf.env"
                                    placeholder="定义环境变量，分号分割，如:FOO=bar;BAZ=tic"></a-input>
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="10">
                        <a-form-item>
                            <div style="display: flex;max-width: 100%;">
                                <label style="display: flex;width: 180px;" class="item-label">
                                    <span>入口命令</span>
                                    <a-tooltip placement="top"
                                        title='指定实例启动时执行的命令，若指定了该项，实例启动则会自动运行该选项，命令执行结果不影响实例创建。例如 "python -m http.server 8080"，则在实例启动时会直接拉起http.server模块，并监听8080端口。'>
                                        <QuestionCircleOutlined style="margin:0 8px 0 4px;color: #D7D9DD;" />
                                    </a-tooltip>
                                </label>
                                <a-input v-model:value="costForm.advancedConf.command"
                                    placeholder="python /root/train.py"></a-input>
                            </div>
                        </a-form-item>
                    </a-col>
                </div>
            </div>

            <div class="page-bottom">
                <div class="page-bot-lf" v-if="['daily', 'weekly', 'monthly'].includes(form.skuName)">
                    <div class="" style="margin-right:16px;">
                        <div class="page-bot-lf-time" style="margin-bottom: 16px;">
                            <div style="margin-right:8px;">时长</div>
                            <a-input-number id="inputNumber" v-if="form.skuName == 'monthly'"
                                v-model:value="costForm.duration" :min="1" :max="12" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'monthly'">月</span>
                            <a-input-number id="inputNumber" v-if="form.skuName == 'daily'"
                                v-model:value="costForm.duration" :min="1" :max="100" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'daily'">日</span>
                            <a-input-number id="inputNumber" v-if="form.skuName == 'weekly'"
                                v-model:value="costForm.duration" :min="1" :max="100" />
                            <span style="margin-left:8px;" v-if="form.skuName == 'weekly'">周</span>
                        </div>
                    </div>

                    <div class="">
                        <div class="ml-32">
                            <span class="normal-title">自动续费
                                <span style="position: relative;">
                                    <QuestionCircleOutlined style="margin:0 4px 0 4px;color: #D7D9DD;font-size: 16px;"
                                        class="autoRenew" />
                                    <div class="autoRenew-box">确保账户余额充足</div>
                                </span>
                            </span>
                            <a-radio-group v-model:value="costForm.autoRenew" name="radioGroup"
                                :disabled="Number(account?.balance) < 2 * instancePayFee">
                                <a-radio value="1">是</a-radio>
                                <a-radio value="0">否</a-radio>
                            </a-radio-group>

                            <a-checkbox v-if="costForm.autoRenew == 0"
                                v-model:checked="costForm.autoPayg">到期后转成自动续费</a-checkbox>
                        </div>
                    </div>
                </div>

                <div class="page-bot-rg">
                    <div class="opt-fee">
                        <div>
                            <div class="total-fee fz-12" style="margin-right: 0;">
                                <span class="mr-16 col-223354" style="position:relative;">存储费用:
                                    <QuestionCircleOutlined style="margin:0 4px 0 4px;color: #D7D9DD;font-size: 16px;"
                                        class="storage-details" />
                                    <div class="storage-details-box">
                                        无论是否关机均会产生的费用，开机<span class="col-money">￥{{ accountInfo?.runningInstanceStoragePrice
                                        }}</span>元/G/小时,关机<span class="col-money">￥{{
    accountInfo?.stopInstanceStoragePrice
}}</span>元/G/小时
                                    </div>
                                    <span class="col-money fz-14">￥{{ formatStorageFee() }}</span>
                                </span>
                                <span class="mr-16 col-223354">实例费用：<span class="col-money fz-14">￥{{ instanceFeesPayable
                                }}</span></span>
                                <span class="mr-16 fz-14 col-223354" style="display:flex;align-items: center;">应付金额：<span
                                        class="col-money fz-22">￥{{ instancePayFee
                                        }}</span></span>
                                <span class="fz-14 col-223354" style="position:relative;">
                                    <span class="free-details col-07F">费用明细</span>
                                    <div class="fee-details-box">
                                        <div><span>实例费用：</span><span class="col-money">￥{{ instancePricePayable }}/{{
                                            formatUnit }}</span>
                                        </div>
                                        <div><span>存储费用：</span><span class="col-money">￥{{ formatStorageSingeFee() }}/{{
                                            formatUnit }}</span></div>
                                        <div><span>系统盘：</span><span class="col-money">￥{{
                                            accountInfo?.runningInstanceStoragePrice || 0 }}</span> * {{
        costForm.SystemDisk }} G</div>
                                        <div><span>数据盘：</span><span class="col-money">￥{{
                                            accountInfo?.runningInstanceStoragePrice || 0 }}</span> * {{
        costForm.DataDisk }} G</div>
                                        <div><span>抵扣代金券：</span><span class="col-money">￥{{ formatTicket() }}</span></div>
                                        <div><span>折扣：</span><span class="col-money">{{
                                            (accountInfo?.userDiscount?.instanceDiscount) * 100 || 0 }}折</span></div>
                                    </div>
                                </span>
                            </div>

                            <div style="display: flex;align-items: center; justify-content: end;">
                                <div class="fz-14 col-223354">
                                    <InfoCircleFilled style="margin-right:5px;" />余额：<span class="fee-style">¥{{
                                        account?.balance }}</span>
                                </div>
                                <div @click="router.push('/recharge')" class="recharge">去充值</div>
                            </div>
                        </div>

                        <a-button type="primary" class="plain-button mr-8" @click="checkInstance"
                            :disabled="!machine?.machineId" style="display:flex;align-item:center;margin-left: 12px;">
                            <svg-icon name="icon_release" class="btn-icon" />
                            创建实例</a-button>
                    </div>
                </div>
            </div>
        </a-spin> -->

        <GpuDrawer v-model="docVisible" v-if="docVisible" :url="docurl"></GpuDrawer>

        <!-- 余额不足弹窗 -->
        <NoBalance v-model="rechargeVisible" v-if="rechargeVisible" :checkData="checkData"></NoBalance>

        <!-- 余额预警弹窗 -->
        <BalanceWarn v-model="balanceWarnVisible" v-if="balanceWarnVisible" :checkData="checkData"
            @handleCreate="onCreateInstance"></BalanceWarn>
    </section>
</template>

<script setup>
import { reactive, ref, watch, computed } from 'vue'
import { getGpuMarket, getImageList, getMyImageList, selectMachine, getImageId } from 'api/modules/api.gpu'
import { createInstance, instanceCheckApi } from 'api/modules/api.instance'
import { getAccountInfoApi } from 'api/modules/api.account'
import userInfoStore from '@/stores/userInfo.js'
import { storeToRefs } from 'pinia'
import { XsyMessage } from '@/libs/util.toast'
import { unitGBS, printSize } from '@/libs/util.common'
import NoBalance from '../components/NoBalance.vue'
import BalanceWarn from '../components/BalanceWarn.vue'
import {
    UpOutlined,
    DownOutlined,
    QuestionCircleOutlined,
    RedoOutlined,
    InfoCircleFilled
} from '@ant-design/icons-vue';
import { useRouter, useRoute } from 'vue-router'
const route = useRoute();
const router = useRouter()

const docVisible = ref(false)
const docurl = ref('')
const openImageDocs = () => {
    docVisible.value = true
    docurl.value = window.location.origin + '/docs/help_document/manual/image/'
}

const openBillTypeDocs = () => {
    docVisible.value = true
    docurl.value = window.location.origin + '/docs/help_document/manual/price'
}

// 镜像列表创建实例
const imageId = route.query.imageId
const maxDataDisk = ref(50)
const costForm = ref({
    machineId: '',
    skuName: '',
    gpuNum: '',
    imageId: '',
    advancedConf: {
        env: '',
        command: ''
    },
    duration: 1,
    autoRenew: null,
    DataDisk: 50,
    SystemDisk: 30
})

const imageType = ref('')

if (imageId) {
    imageType.value = 2
    costForm.value.imageId = imageId
}

// 切换镜像置空
const changeImageType = () => {
    costForm.value.imageId = ''
}

const loading = ref(false) // loading
// 账户余额
const useUserInfoStore = userInfoStore()
const { accountInfo: account } = storeToRefs(useUserInfoStore);

const expand = ref(false)
const isExpansion = ref(false)
const form = ref({
    regionName: '',
    netSpeed: undefined,
    cpuNum: '',
    memory: '',
    // diskType: 'SSD',
    toolVersion: '',
    skuName: 'payg',
    activeTag: [],
    tags: [],
    gpuNum: 1,
    type: 1,
})

const marks = {
    1: '1',
    10: '10',
}

const cuda = ref([])
const regions = ref([])

const activeTags = ref([])
const tags = ref([])
const gpuInfos = ref([])

const initPage = async () => {
    const params = {
        Type: 1
    }

    const res = await getGpuMarket(params)
    cuda.value = res.data.cuda
    // form.value.toolVersion = res.data.cuda?.length && res.data.cuda[0]
    regions.value = res.data.regions
    // form.value.regionId = res.data.regions?.length && res.data.regions[0]?.regionName
    activeTags.value = res.data.activeTags || []
    tags.value = res.data.tags
    gpuInfos.value = res.data.gpuInfos
    // 判断是否可选显卡
    currentGpUName.value = gpuInfos.value.findIndex(item => {
        return item.gpuNum > 0
    })

    if (currentGpUName.value < 0) {
        currentGpUName.value = undefined
        form.value.gpuName = undefined
    } else {
        form.value.gpuName = res.data.gpuInfos?.length && res.data.gpuInfos[currentGpUName.value]?.name
    }

}

// initPage()

// 获取镜像下拉列表

const financialImageList = ref([])
const framework = ref([])
const getFinancialImageList = () => {
    getImageList().then(res => {
        framework.value = res.data.framework
        financialImageList.value = handleData(res.data.framework)
    })
}

// 根据条件筛选镜像ID
const selectImageId = () => {
    if (!costForm.value.image) {
        return
    }
    const [frameName, frameVer, toolVer, runtimeVer] = costForm.value.image
    const params = {
        frameName,
        frameVer,
        toolVer,
        runtimeVer
    }
    getImageId(params).then(res => {
        costForm.value.imageId = res.data.imageId || ''
    })
}

const personalImageList = ref([])
const getPersonalImageList = () => {
    getMyImageList().then(res => {
        personalImageList.value = res.data.Images
    })
}

const handleData = (objData, minVer, maxVer) => {
    const data = { ...objData }
    const arr = []
    arr.push({ label: '框架名称', value: '框架名称', disabled: true })
    for (var i in data) {
        const obj = {}
        obj.label = i
        obj.value = i
        obj.children = []
        obj.children.push({ label: '框架版本', value: '框架版本', disabled: true })
        for (var j in data[i]) {
            const obj1 = {}
            obj1.label = j
            obj1.value = j
            obj1.children = []
            obj1.children.push({ label: 'Cuda版本', value: 'Cuda版本', disabled: true })
            for (var k in data[i][j]) {
                const obj2 = {}
                obj2.label = k
                obj2.value = k
                obj2.disabled = k < minVer || k > maxVer
                obj2.children = data[i][j][k].map(item => {
                    return {
                        label: item,
                        value: item
                    }
                })

                obj2.children.unshift({ label: 'Python版本', value: 'Python版本', disabled: true })
                obj1.children.push(obj2)

            }
            obj.children.push(obj1)
        }

        arr.push(obj)
    }

    return arr
}

// getFinancialImageList()
// getPersonalImageList()

// 付费方式
const currentSkuName = ref('0')
const changeSkuName = (key, name) => {
    costForm.value.autoRenew = null
    currentSkuName.value = key
    name && (form.value.skuName = name)
}

// 选择显卡 
const currentGpUName = ref('0')
const chooseGpu = (key, name) => {
    currentGpUName.value = key
    name && (form.value.gpuName = name)
}

// 根据默认值加载机器信息
const machine = ref({})
const getMachine = async () => {
    const params = {
        ...form.value,
        tags: [...form.value.tags, ...form.value.activeTag]
    }
    const res = await selectMachine(params)
    machine.value = res.data.machine
    dataSource.value = res.data.machine && [res.data.machine]
    maxDataDisk.value = res.data.machine?.availTmpOuotaSize
    financialImageList.value = handleData(framework.value, res.data.machine?.min_Cuda_Version, res.data.machine?.max_Cuda_Version)

}
// 监听机器的条件变化
watch(form.value, (newValue, oldValue) => {
    // 没有显卡不搜索机器
    if (form.value.gpuName) {
        // getMachine()
    }
})

const rechargeVisible = ref(false)
const balanceWarnVisible = ref(false)
const checkData = ref({})
// 创建实例之前先检查费用是否够用
const checkInstance = () => {
    const params = {
        ...costForm.value,
        skuName: form.value.skuName,
        gpuNum: form.value.gpuNum,
        machineId: machine?.value?.machineId || '',
        imageId: costForm.value.imageId,
        autoPayg: costForm.value.autoPayg ? 1 : 0
    }

    loading.value = true

    instanceCheckApi(params).then(res => {
        if (res.code == 0) {
            onCreateInstance()
        } else {
            loading.value = false
        }
    }).catch((err) => {
        loading.value = false
        if (err.code == 10111) {
            rechargeVisible.value = true
            checkData.value = err.data
        } else if (err.code == 10146) {
            balanceWarnVisible.value = true
            checkData.value = err.data
        }
    })
}
const onCreateInstance = () => {
    const params = {
        ...costForm.value,
        skuName: form.value.skuName,
        gpuNum: form.value.gpuNum,
        machineId: machine?.value?.machineId || '',
        imageId: costForm.value.imageId,
        autoPayg: costForm.value.autoPayg ? 1 : 0
    }

    loading.value = true

    createInstance(params).then(res => {
        loading.value = false
        if (res.code == 0) {
            router.push('/instance')
        }
    }).catch((err) => {
        loading.value = false
        if (err.code == 10111) {
            rechargeVisible.value = true
            checkData.value = err.data
        } else if (err.code == 10146) {
            balanceWarnVisible.value = true
            checkData.value = err.data
        }
    })
}

const dataSource = ref([])

const columns = [
    {
        title: 'GPU类型',
        dataIndex: 'gpuName',
        key: 'gpuName',
    },
    {
        title: '地区',
        dataIndex: 'regionName',
        key: 'regionName',
    },
    {
        title: '数量',
        dataIndex: 'gpuNum',
        key: 'gpuNum',
    },
    {
        title: '显存',
        dataIndex: 'vRam',
        key: 'vRam',
    },
    {
        title: '最高CUDA版本',
        dataIndex: 'gpuToolkitVersion',
        key: 'gpuToolkitVersion',
    },
    {
        title: 'CPU型号',
        dataIndex: 'cpuName',
        key: 'cpuName',
    },
    {
        title: 'CPU配置',
        dataIndex: 'cpuCoreNum',
        key: 'cpuCoreNum',
    },
    {
        title: '内存',
        dataIndex: 'memorySize',
        key: 'memorySize',
    },
    {
        title: '网络',
        dataIndex: 'netUploadSpeed',
        key: 'netUploadSpeed',
    },
    {
        title: '价格',
        dataIndex: 'price',
        key: 'price'
    },
    {
        title: '可租赁时间至',
        dataIndex: 'rentEndTime',
        key: 'rentEndTime',
    },
    {
        title: '可用券',
        dataIndex: 'payByVoucher',
        key: 'payByVoucher',
    }
]

// 代金券
const formatTicket = () => {
    const price = machine.value?.price || 0
    const gpuNum = form.value.gpuNum || 0
    const duration = costForm.value.duration || 0
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const voucherFee = machine?.value?.payByVoucher == 1 ? accountInfo?.value?.userTicket?.amount : 0
    const storageTotalFee = formatStorageFee()
    const countFee = (parseFloat(price * gpuNum * duration * discount) + parseFloat(storageTotalFee)) < parseFloat(voucherFee) ? (parseFloat(price * gpuNum * duration * discount) + parseFloat(storageTotalFee)) : parseFloat(voucherFee)

    return countFee.toFixed(2) || 0
}

// 实例存储单价
const formatStorageSingeFee = () => {
    const price = accountInfo?.value?.runningInstanceStoragePrice
    const disk = Number(costForm?.value?.SystemDisk) + Number(costForm?.value?.DataDisk)
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const countFee = price * disk * discount

    return countFee.toFixed(2) || 0
}

// 储存费用  开机存储的单价*（数据盘+系统盘）* 时长
const formatStorageTotalFee = ref(0)
const formatStorageFee = () => {
    const price = accountInfo?.value?.runningInstanceStoragePrice || 0
    const storageNum = Number(costForm?.value?.SystemDisk) + Number(costForm?.value?.DataDisk)
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    let duration = 0

    if (form.value.skuName == 'daily') {
        duration = 1 * 24 * costForm.value.duration
    } else if (form.value.skuName == 'weekly') {
        duration = 1 * 24 * 7 * costForm.value.duration
    } else if (form.value.skuName == 'monthly') {
        duration = 1 * 24 * 30 * costForm.value.duration
    } else {
        duration = 1
    }

    const countFee = price * storageNum * duration * discount
    formatStorageTotalFee.value = countFee.toFixed(2) || 0
    return countFee.toFixed(2) || 0
}



// 费用金额 = 实例价格 + 存储价格
// 实例费用 = 机器sku价格 * 显卡数量 * 租用周期 
const instanceFeesPayable = computed(() => {
    const price = machine.value?.price || 0
    const gpuNum = form.value.gpuNum || 0
    const duration = costForm.value.duration || 0
    const countFee = price * gpuNum * duration
    return countFee.toFixed(2) || 0
})

// 实例价格 = 机器sku价格 * 显卡数量
const instancePricePayable = computed(() => {
    const price = machine.value?.price || 0
    const gpuNum = form.value.gpuNum || 0
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const countFee = price * gpuNum * discount
    return countFee.toFixed(2) || 0
})

// 应付金额 = 实例价格 * 用户折扣 + 存储费用 - 代金券金额
const instancePayFee = computed(() => {
    const price = machine.value?.price || 0
    const gpuNum = form.value.gpuNum || 0
    const duration = costForm.value.duration || 0
    const discount = accountInfo.value?.userDiscount?.instanceDiscount || 1
    const voucherFee = machine?.value?.payByVoucher == 1 ? accountInfo?.value?.userTicket?.amount : 0
    const countFee = (parseFloat(price * gpuNum * duration * discount) + parseFloat(formatStorageTotalFee.value) - parseFloat(voucherFee)) < 0 ? 0 : (parseFloat(price * gpuNum * duration * discount) + parseFloat(formatStorageTotalFee.value) - parseFloat(voucherFee))
    return countFee.toFixed(2) || 0
})

// 转换单位
const formatUnit = computed(() => {
    let str = ''
    if (form.value.skuName == 'daily') {
        str = '天 *' + costForm.value.duration
    } else if (form.value.skuName == 'weekly') {
        str = '周 *' + costForm.value.duration
    } else if (form.value.skuName == 'monthly') {
        str = '月 *' + costForm.value.duration
    } else {
        str = '小时'
    }

    return str
})

// 获取个人账户信息
const accountInfo = ref({})
const getAccountInfo = () => {
    getAccountInfoApi().then(res => {
        accountInfo.value = res.data || {}
    })
}

// getAccountInfo()

</script>

<style scoped lang="scss">

.communityCloud {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.icon-select {
    margin: 0 24px;

    :deep(.ant-select-selector) {
        padding-left: 30px;
    }

    :deep(.ant-select-selector)::before {
        position: absolute;
        left: 8px;
        top: 8px;
    }
}

.page-header {
    position: relative;

    :deep(.ant-space-item)::before {
        height: 2px;
        width: 200px;
        background: #223354;
        position: absolute;
        bottom: 0;
        content: '';
    }
}

.diskType {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_netdisk.svg);
    }
}

.region {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_region.svg);
    }
}

.netSpeed {
    :deep(.ant-select-selector)::before {
        content: url(@/assets/icons/svg/icon_grid.svg);
    }
}

.page-header {
    display: flex;
    padding: 10px;
    background: #fff;
    margin-bottom: 16px;
    justify-content: center;

    .ant-dropdown-trigger {
        margin-right: 50px;
    }
}

.page-key-search {
    padding: 16px 24px 0;
    background: #ffffff;
    margin-bottom: 24px;
}

.page-global-header {
    display: flex;
    margin-bottom: 36px;

    .page-global-title {
        color: #223354;
        font-family: PingFang SC;
        font-size: 18px;
        font-style: normal;
        font-weight: 600;
        line-height: normal;
        padding-right: 8px;
        margin-right: 8px;
    }

    .page-global-title::after {
        display: block;
        content: '';
        height: 5px;
        background: linear-gradient(90deg, #07F 5.32%, rgba(255, 255, 255, 0.00) 103.53%);
    }
}

.page-content {
    padding: 25px;
    background: #fff;
    padding-bottom: 158px;

    .gpu-types {
        display: flex;
        flex-wrap: wrap;

        .gpu-type-card {
            position: relative;
            width: 184px;
            min-height: 80px;
            padding: 14px 0 10px;
            background: #F9FAFC;
            margin-right: 16px;
            margin-bottom: 16px;
            border-radius: 4px;
            border: 1px solid #F9FAFC;

            .title {
                color: #07F;
                text-align: center;
                font-size: 16px;
                font-style: normal;
                font-weight: 600;
                line-height: 26px;
                margin-bottom: 10px;
            }

            p {
                color: #8A93A7;
                font-family: PingFang SC;
                font-size: 12px;
                font-style: normal;
                font-weight: 400;
                line-height: 20px;
                text-align: center;
            }

            .sale-tag {
                position: absolute;
                right: 0;
                top: 0;
                padding: 0 8px;
                height: 20px;
                line-height: 20px;
                border-radius: 2px;
                color: #fff;
                background: linear-gradient(180deg, #FFA291 0%, #FF2452 100%);
            }
        }

        .active-gpu-card {
            background: rgba(0, 119, 255, 0.05);
            border: 1px solid #07F;
        }

        .disabled-gpu-card {
            background: #FAFAFA;

            .title,
            p {
                color: #C1C7D3;
            }
        }
    }

    .billing-modes {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .billing-mode-card {
            width: 184px;
            display: flex;
            margin-right: 16px;
            padding: 8px;
            background: rgba(243, 245, 249, 0.50);
            align-items: center;
            border-radius: 4px;
            cursor: pointer;
            border: 1px solid rgba(243, 245, 249, 0.50);
            margin-bottom: 16px;

            .card-img {
                margin-right: 8px;

                img {
                    display: block;
                    width: 44px;
                    height: 44px;
                }
            }

            .card-info {
                div {
                    color: #223354;
                    font-family: PingFang SC;
                    font-size: 14px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: normal;
                    margin-bottom: 8px;
                }

                p {
                    color: #8A93A7;
                    font-family: PingFang SC;
                    font-size: 12px;
                    font-style: normal;
                    font-weight: 400;
                    line-height: normal;
                }
            }
        }

        .active-mode-card {
            background: rgba(0, 119, 255, 0.05);
            border: 1px solid #07F;
            filter: drop-shadow(0px 2px 6px rgba(202, 196, 196, 0.24));

            .card-info {
                div {
                    color: #07F;
                }
            }
        }
    }

    .expansion {
        display: flex;
        align-items: center;
    }

    .gpuNum {
        position: relative;

        .tooltip {
            position: absolute;
            right: 0;
            top: -10px;
            height: 20px;
            padding: 0 20px;
            border-radius: 2px;
            background: #353535;
            font-size: 12px;
            color: #fff;
            line-height: 20px;
        }
    }
}

.page-bottom {
    position: fixed;
    bottom: 0;
    background: #ffffff;
    border-radius: 2px;
    box-shadow: 0px 0px 10px 0px rgba(155, 174, 201, 0.40);
    width: calc(100% - 220px);
    padding: 24px;
    display: flex;
    justify-content: space-between;
    z-index: 1000;
    padding: 16px 36px 16px 46px;

    .page-bot-lf {

        .page-bot-lf-time {
            display: flex;
            align-items: center;
        }

        .autoRenew-box {
            width: 154px;
            padding: 8px 12px;
            position: absolute;
            background: #ffffff;
            display: none;
            top: -50px;
            left: -60px;
            filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.15));
        }

        .autoRenew:hover+.autoRenew-box {
            display: block;
        }

    }
}

.instance-tips {
    color: #223354;
    font-size: 14px;
    font-style: normal;
    font-weight: 400;
    line-height: 22px;
}

.fee-style {
    color: #FF3D00;
}

.page-bot-rg {
    color: #8A93A7;
    font-family: PingFang SC;
    font-size: 12px;
    font-style: normal;
    font-weight: 400;
    line-height: normal;
    margin-left: auto;

    .total-free-wrap {
        display: flex;
        margin-bottom: 24px;
        justify-content: end;
    }

    .total-fee {
        display: flex;
        align-items: center;

        .storage-details-box {
            min-width: 340px;
            background: #ffffff;
            padding: 8px 12px;
            position: absolute;
            display: none;
            top: -50px;
            left: -170px;
            filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.15));
        }

        .storage-details:hover+.storage-details-box {
            display: block;
        }

        .fee-details-box {
            width: 220px;
            background: #ffffff;
            padding: 15px 20px;
            position: absolute;
            display: none;
            top: -160px;
            left: -110px;
            filter: drop-shadow(0px 2px 8px rgba(0, 0, 0, 0.15));

            div {
                height: 20px;
                line-height: 20px;
            }
        }

        .free-details:hover+.fee-details-box {
            display: block;
        }

    }

    .opt-fee {
        display: flex;
        align-items: center;
        justify-content: end;

        .recharge {
            color: #07F;
            font-size: 18px;
            font-style: normal;
            font-weight: 600;
            line-height: normal;
            margin-left: 12px;
        }
    }
}

.normal-title {
    color: #8A93A7;
    font-size: 14px;
    margin-right: 16px;
}

.ant-form-item {
    :deep(.ant-form-item-label) {
        label {
            width: 140px;
            color: #223354;
            text-align: right;
            font-family: PingFang SC;
            font-size: 14px;
            font-style: normal;
            font-weight: 600;
            line-height: normal;
        }
    }
}

.item-label {
    color: #223354;
    text-align: right;
    font-family: PingFang SC;
    font-size: 14px;
    font-style: normal;
    font-weight: 600;
    line-height: normal;
}

.btn-icon {
    width: 20px;
    height: 20px;
    margin-right: 8px;
    color: #07f;
}

.plain-button:hover {
    .btn-icon {
        color: #ffffff;
    }
}
</style>
